package cn.jekun.web.shop.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.D;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.RsBank;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.SgAccount;
import cn.jekun.component.core.service.SettleApplyService;
import cn.jekun.component.core.service.gen.SgAccountService;
import cn.jekun.web.shop.bean.BanksAccount;
import cn.jekun.web.shop.bean.SgAccounts;
import cn.jekun.web.shop.bean.ShopBusiness;

/**
 * 银行账户管理Service
 *
 */
@Service(BanksService.BEAN_NAME)
public class BanksService extends ShopBaseService{
	public static final String BEAN_NAME="cn.jekun.web.shop.service.BanksAccountService";
	@Resource(name=SettleApplyService.BEAN_NAME)
	protected SettleApplyService settleApplyService;
	@Resource(name=SgAccountService.BEAN_NAME)
	protected SgAccountService sgAccountService;
	@Override
	public String getNamespace() {
		return "SHOP_ADMIN_ACTION_TS_BANKS_ACCOUNTS";
	}

	/**
	 * 获取商户所有绑定的结算账户
	 * @param map
	 * @return
	 */
	public List<ShopBusiness> getBanksAccounts( @ErpShop.AnnoShopId String shopId,Page page){

		Map map=new HashMap<String, String>();
		map.put("shopId", shopId);
		return this.list(this.getStatementName("list"),map,page);

	}


	/**
	 * 获取提现的银行账户信息
	 * @return
	 */
	public BanksAccount getBankAccount(){
		return this.one(this.getStatementName("queryWithdrawBankAccount"),null);
	}

//	/**
//	 * 
//	 * @param userId 用户代码
//	 * @param accountId 提现账户代码
//	 * @param amount 提现金额
//	 * @param amount 提现费用
//	 * @param paypwd 支付密码
//	 * @return 提现申请流水代码
//	 */
//	@Transactional
//	public String settleApply(@RsUser.AnnoUserId String userId,@SgSettleApply.AnnoAccountId String accountId,@SgSettleApply.AnnoAmount double amount,@SgSettleApply.AnnoFee double fee,@TsAccount.AnnoPassword String paypwd){
//		
//		//记录账户流水，增加提现申请
//		String settleApplyId = null;//提现申请代码
//		try {
//			settleApplyId = this.settleApplyService.settleApply(userId,accountId,paypwd,amount,fee,Constants.SG_APPLY_TYPE.SHOP_WEB);//事务 //TODO 通过网站后台提现的，没有流水代码?
//		} catch (Exception e) {
//			e.printStackTrace();
//			if (e instanceof BusinessException) {
//				throw (BusinessException) e;
//			} else {
//				throw new BusinessException(Constants.ERRORS.WITHDRAW_ERROR,"申请提现失败" + e.getMessage());
//			}
//		}
//		return settleApplyId;
//	}
	
	public List<BanksAccount> listSettleApply(@RsUser.AnnoShopId String shopId,@D String beginDate,@D String endDate,@Num(length=10,scale=3) String beginMoney,@Num(length=10,scale=3) String endMoney,@Security String bankName,Page page){
		
//		Map formMap=new HashMap<String, String>();
//		formMap.put("beginDate", beginDate);
//		formMap.put("endDate", endDate);
//		
//		formMap.put("shopId", shopId);
//		SqlUtis.convertBetweenValue(formMap, "commitTime");
//		SqlUtis.prepareSql(formMap
//				,SqlUtis.getSQL(formMap, "a."+SgSettleApply.COL_COMMIT_TIME,"commitTime", Types.DATE)
//				,SqlUtis.getSQL(formMap, "u."+RsUser.COL_REAL_NAME, realName, Types.VARCHAR,SqlUtis.LIKE)
//				,SqlUtis.getSQL(formMap, "u."+RsUser.COL_USER_NAME, userName, Types.VARCHAR,SqlUtis.LIKE)
//				);
		
		String SQL = "";
		if("".equals(beginDate) && !"".equals(endDate)){
			SQL +=" and a.create_time"
					+ "<= to_date('"+beginDate.toString().trim()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginDate) && "".equals(endDate)){
			SQL +=" and a.create_time"
					+ ">= to_date('"+beginDate.toString().trim()+"','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginDate) && beginDate!=null 
				&& !"".equals(endDate) && endDate!=null){
			SQL +=" and a.create_time >= to_date('"+beginDate.toString().trim()+"','yyyy/MM/dd hh24:mi:ss')"
					+ " and a.create_time <= to_date('"+endDate.toString().trim()+" 23:59:59','yyyy/MM/dd hh24:mi:ss')";
		}if(!"".equals(beginMoney) && "".equals(endMoney)){
			SQL +=" and a.amount>="+beginMoney; 
		}if("".equals(beginMoney) && !"".equals(endMoney)){
			SQL +=" and a.amount<="+endMoney; 
		}if(beginMoney!=null && endMoney!=null && !"".equals(beginMoney) 
				&& !"".equals(endMoney)){
			SQL +=" and a.amount>="+beginMoney+" and a.amount<="+endMoney+""; 
		}
		if(bankName!=null && bankName.toString().length()>0){
			SQL +=" and e.BANK_NAME like '%"+bankName.toString()+"%'"; 
		}
		
	    System.out.println("SQL="+SQL);
		Map map=new HashMap();
		map.put("shopId", shopId);
		SqlUtis.prepareSql(map,SQL);
		
		return this.list(this.getStatementName("listSettleApply"), map,page);
	}

	/**
	 * 获取银行列表
	 * @return
	 */
	public List<BanksAccount> getBanks(@RsBank.AnnoBankId String bankId,@RsBank.AnnoBankName String bankName,Page page){
		Map formMap=new HashMap();
		
		String SQL = "";
		
		if(bankId!=null && bankId.toString().length()>0){
			SQL +=" and a.bank_id like '%"+bankId.toString()+"%'"; 
		}
		if(bankName!=null && bankName.toString().length()>0){
			SQL +=" and a.bank_name like '%"+bankName.toString()+"%'"; 
		}
		
	    System.out.println("SQL="+SQL);
		Map map=new HashMap();
		SqlUtis.prepareSql(formMap,SQL);
		
		
		return this.list(this.getStatementName("queryBanks"),formMap,page);
	}

	/**
	 * 获取证件种类列表
	 * @return
	 */
	public List<BanksAccount> getIdCards(){
		return this.list(this.getStatementName("queryidCards"),null);
	}

	/**
	 * 设定为默认结算账户
	 * @param shopId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public boolean setDefaultAccounts(@ErpShop.AnnoShopId String shopId,@SgAccount.AnnoAccountId String accountId){
		try {
			//更新当前商户的其它账户为非默认
			SgAccount updateSgAccount = new SgAccount();
			updateSgAccount.setDefaultFlag("0");
			updateSgAccount.setOwnerId(shopId);
			Map updateMap=new HashMap();
			updateMap.put("sgAccount", updateSgAccount);
			updateMap.put(SgAccount.COL_OWNER_ID, updateSgAccount.getOwnerId());
			SqlUtis.prepareSql(updateMap, "",
					SqlUtis.getSQLRequired(updateMap, "a."+updateSgAccount.COL_OWNER_ID, Types.VARCHAR));
			this.sgAccountService.update(updateMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			SgAccount updateCurrSgAccount = new SgAccount();
			Map map = new HashMap();
			updateCurrSgAccount.setDefaultFlag("1");
			updateCurrSgAccount.setOwnerId(shopId);
			updateCurrSgAccount.setAccountId(accountId);
			map.put("sgAccount",updateCurrSgAccount);
			map.put(SgAccount.COL_OWNER_ID, updateCurrSgAccount.getOwnerId());
			map.put(SgAccount.COL_ACCOUNT_ID, updateCurrSgAccount.getAccountId());
			SqlUtis.prepareSql(map, "",
					SqlUtis.getSQLRequired(map, "a."+updateCurrSgAccount.COL_ACCOUNT_ID, Types.VARCHAR),
					SqlUtis.getSQLRequired(map, "a."+updateCurrSgAccount.COL_OWNER_ID, Types.VARCHAR));
			this.sgAccountService.update(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 绑定银行账户
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public boolean getBindBankCard(@SgAccount.AnnoAccountName String accountName,
								   @SgAccount.AnnoBankId String bankId,
								   @SgAccount.AnnoBankNumber String bankNumber,
								   @SgAccount.AnnoDefaultFlag String defaultaccount,
								   @ErpShop.AnnoShopId String shopId){
		Map map = new HashMap();
		try {
			SgAccounts sgAccounts = new SgAccounts();
			sgAccounts.setOwnerTypeId(Constants.TS_ACCOUNT_OWNER_TYPE.SHOP);//户主类型
			sgAccounts.setOwnerId(shopId); //户主代码
			sgAccounts.setAccountTypeId(Constants.TS_ACCOUNT_TYPE.SETTLE); //账户类型
			sgAccounts.setAccountName(accountName);
			sgAccounts.setBankId(bankId);
			sgAccounts.setBankNumber(bankNumber);
//			sgAccounts.setIdentifyTypeId(identifyTypeId);
//			sgAccounts.setIdentity(identity);
			sgAccounts.setBankNumber(bankNumber);
//			sgAccounts.setMobile(mobile);
			sgAccounts.setAccountType("00");
			//是否存在默认的银行卡
			Map existsMap=new HashMap();
			existsMap.put(SgAccount.COL_OWNER_ID, sgAccounts.getOwnerId());
			existsMap.put(SgAccount.COL_OWNER_TYPE_ID, sgAccounts.getOwnerTypeId());
			existsMap.put(SgAccount.COL_DEFAULT_FLAG, "1");
			SqlUtis.prepareSql(existsMap, "",
					SqlUtis.getSQLRequired(existsMap, "a."+SgAccount.COL_OWNER_ID, Types.VARCHAR)
					,SqlUtis.getSQLRequired(existsMap, "a."+SgAccount.COL_OWNER_TYPE_ID, Types.VARCHAR)
					,SqlUtis.getSQLRequired(existsMap, "a."+SgAccount.COL_DEFAULT_FLAG, Types.VARCHAR)
					);
			if(!sgAccountService.exists(existsMap)){
				sgAccounts.setDefaultFlag("1"); //是否默认为结算账户(提现标志) 1-是/0-否
			}else{
				if(defaultaccount!=null && "1".equals(defaultaccount)){
					//更新当前商户的其它账户为非默认
					SgAccount updateSgAccount = new SgAccount();
					updateSgAccount.setDefaultFlag("0");
					sgAccounts.setDefaultFlag("1"); //是否默认为结算账户(提现标志) 1-是/0-否
					updateSgAccount.setOwnerId(shopId);
					Map updateMap=new HashMap();
					updateMap.put("sgAccount", updateSgAccount);
					updateMap.put(SgAccount.COL_OWNER_ID, updateSgAccount.getOwnerId());
					updateMap.put(SgAccount.COL_OWNER_TYPE_ID, Constants.TS_ACCOUNT_OWNER_TYPE.SHOP);
					SqlUtis.prepareSql(updateMap, ""
								,SqlUtis.getSQLRequired(updateMap, "a."+SgAccount.COL_OWNER_ID, Types.VARCHAR)
								,SqlUtis.getSQLRequired(updateMap, "a."+SgAccount.COL_OWNER_TYPE_ID, Types.VARCHAR)	
								);
					this.sgAccountService.update(updateMap);		
				}else{
					sgAccounts.setDefaultFlag("0"); //是否默认为结算账户(提现标志) 1-是/0-否	
				}
			}
			sgAccounts.setAvailable("1"); //有效标志  1-有效/0-无效、解绑
			map.put("sgAccounts", sgAccounts);
			this.insert(map);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return true;
	}
	
	
	/**
	 * 解除绑定
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public boolean updateSgAccount(@SgAccount.AnnoDefaultFlag String defaultFlag,
							   	   @SgAccount.AnnoAvailable String available,
							   	   @NotBlank @SgAccount.AnnoAccountId String accountId){
		Map map = new HashMap();
		SgAccount sgAccount=new SgAccount();
		if(defaultFlag!=null){
			sgAccount.setDefaultFlag(defaultFlag); //是否默认为结算账户(提现标志) 1-是/0-否
		}
		if(available!=null){
			sgAccount.setAvailable(available); //有效标志  1-有效/0-无效、解绑
		}
		map.put("sgAccount", sgAccount);
		map.put(SgAccount.COL_ACCOUNT_ID, accountId);
		SqlUtis.prepareSql(map, "",
				SqlUtis.getSQLRequired(map, "a."+SgAccount.COL_ACCOUNT_ID, Types.VARCHAR));
		this.sgAccountService.update(map);

		return true;
	}
	
	
	

	/**
	 * 判断是否有相同卡号
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean isBanksNumber(@SgAccount.AnnoBankNumber String bankNumber){
		SgAccount querysg = new SgAccount();
		Map isnumbermap = new HashMap();
		querysg.setBankNumber(bankNumber);
		isnumbermap.put(querysg.COL_BANK_NUMBER, querysg.getBankNumber()); //where条件值,put->Map
		isnumbermap.put("sgAccount", querysg);
		SqlUtis.prepareSql(isnumbermap,
				SqlUtis.getSQL(isnumbermap, "a."+querysg.COL_BANK_NUMBER, Types.VARCHAR));
		return this.sgAccountService.count(isnumbermap)>0?true:false;
	}
	
	/**
	 * 判断当前账户是否是唯一结算账户
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean isDefaultAccount(@SgAccount.AnnoAccountId String accountId){
	  SgAccount sgAccount = new SgAccount();
	  Map accountmap = new HashMap();
	  sgAccount.setDefaultFlag("1");
	  sgAccount.setAccountId(accountId);
	  accountmap.put(sgAccount.COL_DEFAULT_FLAG, sgAccount.getDefaultFlag()); ////where条件值,put->Map
	  accountmap.put(sgAccount.COL_ACCOUNT_ID, sgAccount.getAccountId()); 
	  accountmap.put("sgAccount", sgAccount); //单表操作,map-key值需与对应的配置ibatis-xml配置文件匹配
	  SqlUtis.prepareSql(accountmap, SqlUtis.getSQL(accountmap, "a."+sgAccount.COL_DEFAULT_FLAG,Types.VARCHAR)
			  , SqlUtis.getSQL(accountmap, "a."+sgAccount.COL_ACCOUNT_ID,Types.VARCHAR));
	  return this.sgAccountService.count(accountmap)==1?true:false;	  
	}

}
